<?php
/**
 * @author Tongle Xu <xutongle@gmail.com>
 * @copyright Copyright (c) 2003-2103 Jinan TintSoft development co., LTD
 * @license http://www.tintsoft.com/html/about/copyright/
 * @version $Id$
 */
namespace Leaps\Base;

use Leaps;

/**
 * 所有控制器操作类的基类。
 *
 * Action provides a way to divide a complex controller into
 * smaller actions in separate class files.
 *
 * Derived classes must implement a method named `run()`. This method
 * will be invoked by the controller when the action is requested.
 * The `run()` method can have parameters which will be filled up
 * with user input values automatically according to their names.
 * For example, if the `run()` method is declared as follows:
 *
 * ~~~
 * public function run($id, $type = 'book') { ... }
 * ~~~
 *
 * And the parameters provided for the action are: `['id' => 1]`.
 * Then the `run()` method will be invoked as `run(1)` automatically.
 *
 * @property string $uniqueId The unique ID of this action among the whole application. This property is
 * read-only.
 *
 * @author Tongle Xu <xutongle@gmail.com>
 * @since 4.0
 */
class Action extends Component
{
	/**
	 * 动作ID
	 * @var string ID of the action
	 */
	public $id;

	/**
	 * 拥有此操作的控制器
	 * @var Controller the controller that owns this action
	 */
	public $controller;

	/**
	 * 构造方法
	 * @param string $id the ID of this action
	 * @param Controller $controller the controller that owns this action
	 * @param array $config name-value pairs that will be used to initialize the object properties
	 */
	public function __construct($id, $controller, $config = [])
	{
		$this->id = $id;
		$this->controller = $controller;
		parent::__construct($config);
	}

	/**
	 * 返回此操作的惟一的ID在整个应用程序。
	 * @return string the unique ID of this action among the whole application.
	 */
	public function getUniqueId()
	{
		return $this->controller->getUniqueId() . '/' . $this->id;
	}

	/**
	 * 从指定的参数运行该操作。
	 * This method is mainly invoked by the controller.
	 * @param array $params the parameters to be bound to the action's run() method.
	 * @return mixed the result of the action
	 * @throws InvalidConfigException if the action class does not have a run() method
	 */
	public function runWithParams($params)
	{
		if (!method_exists($this, 'run')) {
			throw new InvalidConfigException(get_class($this) . ' must define a "run()" method.');
		}
		$args = $this->controller->bindActionParams($this, $params);
		Leaps::trace('运行操作: ' . get_class($this) . '::run()', __METHOD__);
		if (Leaps::$app->requestedParams === null) {
			Leaps::$app->requestedParams = $args;
		}
		return call_user_func_array([$this, 'run'], $args);
	}
}
